import { Component, OnInit, Injector } from '@angular/core';
import { map } from 'rxjs/operators';
import { DetailBase } from 'app/modules/base/detail-base';
import {
  PersonnelService,
  UserStatus,
  Personnel,
  PersonnelInfo,
  UserPermission,
} from '../../services/personnel.service';
import { ResetPasswordComponent } from '../reset-password/reset-password.component';
import { MySelection } from 'app/modules/base/selection';
import { Zone } from 'app/modules/zone/services/zone.service';

@Component({
  selector: 'm-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.scss'],
})
export class DetailsComponent extends DetailBase implements OnInit {
  constructor(private injector: Injector, private personnelService: PersonnelService) {
    super(injector);
  }
  editing = false;
  personnel$ = this.getData<PersonnelInfo>('personnel');
  permission$ = this.personnel$.pipe(map(p => this.personnelService.permission(p.id)));
  usedComputer$ = this.personnel$.pipe(map(p => this.personnelService.usedComputer(p.id)));
  usedSoftware = this.personnelService.usedSoftware();
  Status = UserStatus;
  permissionSelection = new MySelection<UserPermission>('id');

  ngOnInit() {}

  edited() {
    this.editing = false;
    this.reload();
  }
  async disable(id: number) {
    if ((await this.sweet.confirm('确定要停用吗')).dismiss) {
      return;
    }
    await this.personnelService.batch('status', UserStatus.Disable, [id]);
    this.reload();
  }
  async enable(id: number) {
    if ((await this.sweet.confirm('确定要启用吗')).dismiss) {
      return;
    }
    await this.personnelService.batch('status', UserStatus.Enable, [id]);
    this.reload();
  }
  async delete(personnel: Personnel) {
    const result = await this.sweet.confirm(`确定要删除人员${personnel.full_name}吗`);
    if (result.value) {
      await this.personnelService.delete([personnel.id]);
      this.back();
    }
  }
  async reset(personnel: Personnel) {
    this.dialog.open(ResetPasswordComponent, {
      width: '30rem',
    }).componentInstance.personnel = personnel;
  }

  get personnel() {
    return this.route.snapshot.data['personnel'] as PersonnelInfo;
  }

  async deleteAuth(aid?: number) {
    if (aid) {
      return this.personnelService.authDelete(this.personnel.id, [aid]);
    }
    await this.personnelService.authDelete(this.personnel.id, this.permissionSelection.keys());
    this.permissionSelection.clear();
  }
  async authStatus(status: UserStatus, ...zid: number[]) {
    if (!zid.length) {
      zid = this.permissionSelection.keys();
    }
    return this.personnelService.authStatus(this.personnel.id, zid, status);
  }

  permission(zone: Zone) {
    this.personnelService.permissionNav(zone, [this.personnel.id]);
  }
}
